package com.yjha.lzmarathonsys.consumer;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.rabbitmq.client.Channel;
import com.yjha.lzmarathonsys.bean.TbLike;
import com.yjha.lzmarathonsys.config.RabbitmqConfig;
import com.yjha.lzmarathonsys.mapper.TbLikeMapper;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Date;
import java.util.Map;

@Component
public class LikeConsumer {
    @Autowired
    private TbLikeMapper likeMapper;

    @RabbitListener(queues = RabbitmqConfig.QUEUE_LIKE)
    public void processLikeMessage(Map<String, Object> msg, Channel channel, Message message) throws IOException {
        try {
            String userId = (String) msg.get("userId");
            String targetId = (String) msg.get("targetId");
            int action = (Integer) msg.get("action");
            Date createTime = new Date((Long) msg.get("timestamp"));

            // 幂等性检查（关键！）
            QueryWrapper<TbLike> checkWrapper = new QueryWrapper<>();
            checkWrapper.eq("user_id", userId)
                    .eq("target_id", targetId);
            boolean exists = likeMapper.exists(checkWrapper);

            if (action == 1) {
                if (!exists) {
                    TbLike like = new TbLike();
                    like.setUserId(userId);
                    like.setTargetId(targetId);
                    like.setCreatedAt(createTime);
                    likeMapper.insert(like);
                }
            } else {
                if (exists) {
                    likeMapper.delete(checkWrapper);
                }
            }

            // 手动ACK确认
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            // 错误处理（记录日志 + 重试）
            channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
        }
    }
}
